import { useEffect } from 'react';
import { useLocation, Navigate, useRoutes } from 'react-router-dom';
import routes from '@/router/routes';
import { default as pubsub, ROUTER_BEFOREEACH } from '@/utils/pubsub';
import { ReactRouterProps, RouterBeforeEachProps } from './model';

pubsub.on(ROUTER_BEFOREEACH, (route: ReactRouterProps) => {
    console.log('i am beforeEach - on actual route change');
    if (!route.element && !route.Component) {
        route.element = <Navigate to={'/404'}></Navigate>;
        return;
    }
    if (route.name && ['login', '404'].includes(route.name.toLocaleLowerCase())) {
        return;
    }
    if (true) {
        // route.element = <Navigate to={'/login'}></Navigate>;
    }
});

const RouterBeforeEach: React.FC<RouterBeforeEachProps> = ({ route, children }: RouterBeforeEachProps) => {
    const location = useLocation();
    useEffect(() => {
        // 这里执行您需要在路由变化时执行的逻辑
        pubsub.emit(ROUTER_BEFOREEACH, route);
    }, [location.pathname]);
    return children;
};

const resolveRoutes = (routes: ReactRouterProps[]) => {
    return routes.map((route: ReactRouterProps) => {
        if (route.children) {
            route.children = resolveRoutes(route.children);
        }
        if (route.redirect) {
            route.element = <Navigate to={route.redirect} />;
        } else if (route.element || route.Component) {
            route.element = <RouterBeforeEach route={route}>{route.Component ? <route.Component /> : route.element}</RouterBeforeEach>;
        }
        return route;
    });
};

export default function Router() {
    return useRoutes(routes);
}
